//
//  NewUiscrollerView.m
//  UI11home
//
//  Created by apple on 15/11/9.
//  Copyright © 2015年 liyinkai. All rights reserved.
//

#import "NewUiscrollerView.h"

@implementation NewUiscrollerView
-(void)dealloc {
    [_array release];
    [super dealloc];
}
-(instancetype)initWithFrame:(CGRect)frame witharray:(NSArray *)array{
    if (self = [super initWithFrame:frame]) {
        _array = [[NSMutableArray alloc] initWithArray:array];
        [self createScrollView];
    }
    return self;
}

-(void)createScrollView {
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:self.bounds];
    scroll.pagingEnabled = YES;
    scroll.tag = 1001;
    if (self.array.count) {
        [_array insertObject:[_array lastObject] atIndex:0];
        [_array addObject:_array[1]];
        for (int i = 0; i < _array.count; i++) {
            UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(self.frame.size.width * i, 0, self.frame.size.width, self.frame.size.height)];
            image.image = [UIImage imageNamed:_array[i]];
            //            保持图片的比例不变
            image.contentMode = UIViewContentModeScaleAspectFill;
            image.clipsToBounds = YES;
            [scroll addSubview:image];
            [image release];
        }
    }
    scroll.delegate = self;
    scroll.contentOffset = CGPointMake(self.frame.size.width, 0);
    scroll.contentSize = CGSizeMake(self.bounds.size.width * _array.count, 0);
    [self addSubview:scroll];
    [scroll release];
    _num = 2;
    NSTimer *time = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timer) userInfo:nil repeats:YES];
}
-(void)timer {
    
    UIScrollView *scroll = (UIScrollView *)[self viewWithTag:1001];
    [scroll setContentOffset:CGPointMake(scroll.contentOffset.x + self.frame.size.width, 0) animated:YES];
    if (scroll.contentOffset.x == 0) {
        [scroll setContentOffset:CGPointMake(self.frame.size.width * (_array.count - 2), 0)];
    }
    if (scroll.contentOffset.x == self.frame.size.width * (_array.count - 1)) {
        [scroll setContentOffset:CGPointMake(self.frame.size.width , 0)];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.x == 0) {
        [scrollView setContentOffset:CGPointMake(self.frame.size.width * (_array.count - 2), 0)];
    }
    if (scrollView.contentOffset.x == self.frame.size.width * (_array.count - 1)) {
        [scrollView setContentOffset:CGPointMake(self.frame.size.width , 0)];
    }
    _num = (scrollView.contentOffset.x / self.frame.size.width);
}
@end
